package main.java.web.servlet;

import main.java.domain.Task;
import main.java.service.TaskService;
import main.java.service.impl.TaskServiceImpl;
import main.java.utils.DownloadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 文件下载
        // 获取请求参数
        String filename = request.getParameter("filename");

        ServletContext servletContext = request.getServletContext();

        // 获取文件路径
        HttpSession session = request.getSession();
        Task task = (Task)session.getAttribute("task");

        // 字节流连接
        FileInputStream fis = new FileInputStream(filename);

        // 获取MIME
        String MIME = servletContext.getMimeType(filename);

        // 截取文件名
        String[] file = filename.split("/");

        // 中文编码问题
        String agent = request.getHeader("user-agent");
        filename = DownloadUtils.getFileName(agent, file[file.length-1]);

        System.out.println(file[file.length-1]);

        // 设置响应头
        response.setHeader("Content-Type", MIME);
        response.setHeader("Content-Disposition", "attachment;filename="+filename);

        // 读取流
        ServletOutputStream os = response.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while ((len = fis.read(buff)) != -1){
            os.write(buff, 0, len);
        }

        // 关闭输入流
        fis.close();
    }
}
